﻿using System;
using System.Net.Mail;
using NOSDC.Models;
using System.Text;

namespace NOSDC.Utility
{
    public sealed class Mail
    {
        public const string BUG_EMAIL = "rick.wt@gmail.com";
        public const string CONTACT_EMAIL = "rick.wt@gmail.com";

        public static void SendContactEmail(ContactUs contact)
        {
            var sb = new StringBuilder();

            sb.Append("Contact Us\r\n\r\n");
            sb.Append("Subject: " + contact.Subject + "\r\n");
            sb.Append("From: " + contact.Name + "\r\n");
            sb.Append("Their Email: " + contact.From + "\r\n");
            sb.Append("\r\n\r\n" + contact.Message);

            SendMail(CONTACT_EMAIL, contact.Subject, sb.ToString());
        }

        public static void SendBugEmail(Exception e, string url)
        {
            var sb = new StringBuilder();
            sb.Append("Error\r\n\r\n");
            sb.Append("Message: " + e.Message + "\r\n");
            sb.Append("-----------------------------------------------------------------------------\r\n");
            sb.Append("Stack Trace: " + e.StackTrace + "\r\n\r\n");
            sb.Append("Source: " + e.Source + "\r\n");

            SendMail(BUG_EMAIL, "Bug Report", sb.ToString());
        }

        private static void SendMail(string to, string subject, string body)
        {
            try
            {
                var mailMessage = new MailMessage();
                mailMessage.To.Add(to);
                mailMessage.Subject = subject;
                mailMessage.Body = body;
                mailMessage.From = new MailAddress("noreply@nosdc.net");

                var smtpClient = new SmtpClient();

                smtpClient.Send(mailMessage); 
            }
            catch (Exception)
            {
                //just here to prevent an endless loop, only error that should ever occur here is smtp not available or the credentials are wrong.
            }
        }

        internal static void SendRecoveryEmail(string to, string recoveryLink)
        {
            var sb = new StringBuilder();
            sb.Append("In order to reset your password for NOSDC, visit the following link.\r\n\r\n");
            sb.Append(recoveryLink);
            sb.Append("\r\n");
            sb.Append("This link will be valid for 24 hours. If you weren't trying to reset your password, you can ignore this email.Your account is still secure and no one has been given access to it. ");
     
            SendMail(to, "NOSDC - Password recovery", sb.ToString());
        }
    }
}